import type { RouteRecordRaw } from 'vue-router';
import { defineStore } from 'pinia';
import { store } from '@/store';
import { login, getUserInfo } from '@/api/login';
import { ACCESS_TOKEN_KEY } from '@/framework/enums/cacheEnum';
import { Storage } from '@/framework/utils/Storage';
import { logout } from '@/api/account';
import { generateMenu } from '@/router/generator-router';
import { useWsStore } from '@/framework/store/ws';
import { resetRouter } from '@/router';
import FuncInfo = API.FuncInfo;

enum LOGIN_TYPE {
  LOCAL,
  SSO,
}

interface UserState {
  token: string;
  name: string;
  organizationid: '';
  roles: Array<API.RoleInfo>;
  perms: string[];
  menus: RouteRecordRaw[];
  userInfo: Partial<API.AdminUserInfo>;
  loginType: LOGIN_TYPE;
  // 外部系统，应用于单点模式下，子系统间跳转
  outerSystems: SSO.SystemInfo[];
  funcs: FuncInfo[];
  organization: any;
}

export const useUserStore = defineStore({
  id: 'user',
  state: (): UserState => ({
    token: Storage.get(ACCESS_TOKEN_KEY, null),
    name: 'amdin',
    perms: [],
    organizationid: '',
    menus: [],
    userInfo: {},
    loginType: LOGIN_TYPE.LOCAL,
    outerSystems: [],
    funcs: [],
    organization: {},
    roles: [],
  }),
  getters: {
    getToken(): string {
      return this.token;
    },
    getName(): string {
      return this.name;
    },
    getPerms(): string[] {
      return this.perms;
    },
    getOrganizationInfo(): API.OrganizationInfo {
      return this.organization;
    },
    getRoles(): Array<API.RoleInfo> {
      return this.roles;
    },
  },
  actions: {
    // 清空token及用户信息
    resetToken() {
      this.perms = [];
      this.menus = [];
      this.userInfo = {};
      Storage.clear();
      Storage.removeCookie('token');
    },
    // 登录成功保存token
    setToken(token: string) {
      this.token = token ?? '';
      const ex = 7 * 24 * 60 * 60 * 1000;
      Storage.set(ACCESS_TOKEN_KEY, this.token, ex);
    },
    // 登录
    async login(params: API.LoginParams) {
      try {
        const res: any = await login(params);
        this.setToken(res?.result?.token);
        return this.afterLogin();
      } catch (error) {
        return Promise.reject(error);
      }
    },
    // 登录成功之后, 获取用户信息以及生成权限路由
    async afterLogin() {
      try {
        const res = await getUserInfo();
        const { attributes, roles, funcs, user, organization } = res.result;
        this.name = user.username;
        this.organizationid = organization?.id || '';
        this.userInfo = user;
        this.funcs = user.id === 'superadmin' ? [] : funcs;
        this.organization = organization;
        this.roles = roles;
        // // 生成路由∂
        console.log(funcs, 'funcs');
        const generatorResult = generateMenu(this.funcs[0]?.children || []); // this.funcs[0].children!
        this.menus = generatorResult.menus;
        // let user = {
        //   id: 'superadmin',
        //   name: 'superadmin',
        //   username: 'superadmin',
        // };
        // let menus = [
        //   {
        //     component: () => import('/src/pages/home/index.vue'),
        //     meta: {
        //       fullPath: '/home',
        //       icon: 'icon-home',
        //       namePath: ['home'],
        //       title: 'routes.home.home',
        //     },
        //     name: 'home',
        //     path: '/home',
        //   },
        // ];

        return { userInfo: user, menus: generatorResult.menus };
      } catch (error) {
        // return this.logout();
      }
    },
    // 登出
    async logout() {
      await logout();
      const wsStore = useWsStore();
      wsStore.closeSocket();
      this.resetToken();
      resetRouter();
    },
  },
});

// 在组件setup函数外使用
export function useUserStoreWithOut() {
  return useUserStore(store);
}
